<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/28 0028
 * Time: 13:50
 */

namespace app\api\controller;


use app\admin\model\Couponuse;
use app\admin\model\User;
use app\admin\model\Store;
use app\admin\model\Coupon AS CouponMdl;

class Coupon extends BaseController
{
    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 商家优惠券列表
     */
    public function getTenantCoupon()
    {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能为空');
        } else if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId不能为空');
        } else {
            $tenantId = $param->tenantId;
            $storeId = $param->storeId;
            $curTime = time();
            $coup = CouponMdl::where(['tenantId'=>$tenantId,'storeId'=>$storeId])->where('endTime > '.$curTime.' and getCond = 1')->where('leftCount > 0 or isLimit = 1')->select();  //查询未过期的可领取的优惠券
            if (empty($coup)) {
                return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到优惠券');
            } else {
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $coup);
            }
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取我的优惠券
     */
    public function getMyCoupon()
    {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能为空');
        } else if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId不能为空');
        } else {
            $tenantId = $param->tenantId;
            $userId = $param->userId;
            $storeId = $param->storeId;
            if (empty($param->status)) {
                $status = 0;
            } else {
                $status = $param->status;
            }
            $storeList = Store::field('id,name')->where(['tenantId' => $tenantId])->select();
            $storeMap = [];
            foreach ($storeList as $s) {
                $storeMap[$s['id']] = $s['name'];
            }

            if ($status == 0) {
                $couponUse = Couponuse::where(['tenantId' => $tenantId, 'userId' => $userId, 'status' => 0,'storeId'=>$storeId])->select();
                if (empty($couponUse)) {
                    return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到优惠券');
                } else {
                    $coupon = [];
                    foreach ($couponUse as $use) {
                        $coup = json_decode($use['couponDetail'],true);
                        $coup['storeName'] = $storeMap[$use['storeId']];
                        if($coup['endTime'] > time()) {
                            array_push($coupon, $coup);
                        }
                        // $coup = \app\admin\model\Coupon::where(['id' => $use->couponId])->find();
                        // if (!empty($coup) && strtotime($coup->endTime) > time()) {
                        //     array_push($coupon, $coup);
                        // }
                    }
                    if (count($coupon) > 0) {
                        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $coupon);
                    } else {
                        return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到优惠券');
                    }
                }
            } else if ($status == 1) {
                $couponUse = Couponuse::where(['tenantId' => $tenantId, 'userId' => $userId, 'status' => 1,'storeId'=>$storeId])->select();
                if (empty($couponUse)) {
                    return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到优惠券');
                } else {
                    $coupon = [];
                    foreach ($couponUse as $use) {
                        $coup = json_decode($use['couponDetail'],true);
                        $coup['storeName'] = $storeMap[$use['storeId']];
                        if($coup['endTime'] > time()) {
                            array_push($coupon, $coup);
                        }
                    }
                    if (count($coupon) > 0) {
                        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $coupon);
                    } else {
                        return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到优惠券');
                    }
                }
            } else {
                $couponUse = Couponuse::where(['tenantId' => $tenantId, 'userId' => $userId,'status'=>0,'storeId'=>$storeId])->select();
                if (empty($couponUse)) {
                    return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到优惠券');
                } else {
                    $coupon = [];
                    foreach ($couponUse as $use) {
                        $coup = json_decode($use['couponDetail'],true);
                        $coup['storeName'] = $storeMap[$use['storeId']];
                        if($coup['endTime'] < time()) {
                            array_push($coupon, $coup);
                        }
                    }
                    if (count($coupon) > 0) {
                        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $coupon);
                    } else {
                        return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到优惠券');
                    }
                }
            }
        }
    }

    /**
     * 用户领取优惠券
     * @param    string     $userId 用户ID
     * @param    string     $tenantId 店铺ID
     * @param    string     $couponId 优惠券ID
     */
    public function receiveCoupon() {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能为空');
        } else if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId不能为空');
        } else if (empty($param->couponId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'couponId不能为空');
        }
        $couponId = $param->couponId;
        $userId = $param->userId;
        $tenantId = $param->tenantId;

        $coupon = CouponMdl::where('id',$couponId)->find()->toArray();
        if(!$coupon) {
             return show(config('status.ERROR_STATUS'), '优惠券不存在',[]);
        }
        if($coupon['endTime'] < time()) {
            return show(config('status.ERROR_STATUS'), '此优惠券已过期',[]);
        }
        if($coupon['isLimit'] == 2 && $coupon['receiveCount'] >= $coupon['totalCount']) {  //限量
            return show(config('status.ERROR_STATUS'), '此优惠券已被领完',[]);
        }
        
        $getCount = Couponuse::where(['userId'=>$userId,'couponId'=>$couponId])->count();  //查询用户已领取且未使用的此优惠券的数量
        // return $getCount;
        if($getCount >= $coupon['maxGet']) {
            return show(config('status.ERROR_STATUS'), '超过数量限制，请领取其他优惠券',[]);
        }
        $find = Couponuse::where(['userId'=>$userId,'couponId'=>$couponId,'status'=>0])->find();  //此优惠券用户已领取但未使用
        if($find) {
            $find->toArray();
            $name = json_decode($find['couponDetail'],true);
            return show(config('status.ERROR_STATUS'), '您尚有一张'.$name['name'].'的优惠券，请先使用后再领取',[]);
        }
        if($coupon['isGetPhone'] == 1) {  //验证手机号
            $user = User::where('id',$userId)->find();
            if(empty($user['mobile'])) {
                return show(3, '您还未绑定手机，请先绑定',[]);
            }
        }

        $data = [
            'id' => get_uniqid_id(),
            'userId' => $userId,
            'tenantId' => $tenantId,
            'storeId' => $coupon['storeId'],
            'couponId' => $couponId,
            'createDate' => time(),
            'couponDetail' => json_encode($coupon)
        ];
        if(Couponuse::insert($data)) {
            if($coupon['isLimit'] == 2) {  //有总量限制的，剩余数量减1
                CouponMdl::where('id', $couponId)->setDec('leftCount');  
            }
            CouponMdl::where('id', $couponId)->setInc('receiveCount');   //领取数量加1
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS,[]);
        } else {
            return show(config('status.ERROR_STATUS'), ' 网络出错，请重试',[]);
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getCanUseCoupons()
    {
        $param = self::getHttpParam();
        if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId不能为空');
        } else if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId不能为空');
        } else if (empty($param->price)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'price不能为空');
        } else {
            $storeId = $param->storeId;
            $userId = $param->userId;
            $price = $param->price;
            $coupon = [];
            $couponuseMdl = new couponUse();
            $couponUse = $couponuseMdl->where(['storeId' => $storeId, 'userId' => $userId, 'status' => 0])->select();
            foreach ($couponUse as $use) {
                $coup = json_decode($use['couponDetail'],true);   //根据领取时的优惠券信息计算

                //return $coup;
                // array_push($coupon, $coup);
                // $coup = \app\admin\model\Coupon::where('id', $use->couponId)->where('value1', '<', $price)->find();
                
                if (($coup['type'] == '无限制' || ($coup['type'] == '消费满减' && $coup['value1'] <= $price)) && ($coup['endTime'] > time())  && ($coup['startTime'] <= time()) && $couponuseMdl->checkTime($coup)){  //满足订单金额和使用时段
                    array_push($coupon, $coup);
                }
            }

            if (empty($coupon)) {
                return show(config('status.SUCCESS_STATUS'), "暂无可用的优惠券", []);
            } else {
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $coupon);
            }
        }
    }


}